<template>
  <div class="home-page-container">
    <!--查询没权限的情况-->
    <div v-if="tableData.display === true">
      <!--搜索条件-->
      <div class="content-search">
        <!--company: true 商户 false 油站-->
        <div class="search-oilstation" v-if="loginInfo.company">
          <span class="label-text">油站名称</span>
          <el-select filterable placeholder="请选择" v-model="params.gasId" @change="oilStationChange" size="mini">
            <el-option
                v-for="item in oilStations"
                :key="item.gasId"
                :label="item.gasName"
                :value="item.gasId"
            >
            </el-option>
          </el-select>
        </div>
        <div class="search-box">
          <div class="search-item">
            <!--  时间标签选项区域-->
            <div class="btn-box" >
              <div :class="['btn', {'active': item.code === selectedTime}]" v-for="(item, index) in searchList" :key="index" @click="selectTime(item)">{{item.value}}</div>
            </div>
            <!--分割线-->
            <div class="line"></div>
            <!-- 状态选择区域-->
            <div class="btn-box">
              <div :class="['btn', {'active': item.code === selectedStatus}]"  v-for="(item, index) in statusList" :key="index" @click="selectStatus(item)">{{item.value}}</div>
            </div>
          </div>
          <div class="all">
            <!--全部按钮-->
            <el-button type="primary" class="active" @click="queryAllDataList">全部</el-button>
          </div>
        </div>
      </div>
      <div class="operation-box">
        <el-button @click="add">新增</el-button>
      </div>
      <!-- table 表格 -->
      <el-card shadow="never">
        <el-table v-loading="loading" border stripe size="small" :data="tableData.items" style="width: 100%;height:100%;" highlight-current-row>
          <slot name="table"></slot>
          <el-table-column type="index" label="序号" width="66" fixed="left" align="center">
            <template slot-scope="scope">
              {{scope.$index+(params.pageNum - 1) * params.pageSize + 1}}
            </template>
          </el-table-column>
          <template v-for="(item,index) in tableConfig">
            <el-table-column v-if="!item.slot"  :label="item.label" :prop="item.prop" :min-width="item.width" :fixed="item.fixed" :key="index" align='center'></el-table-column>
            <el-table-column v-if="item.slot" :label="item.label" :prop="item.prop" :min-width="item.width" :fixed="item.fixed" :key="index" align='center'>
              <template slot-scope="{row}">
                <slot :name="item.slot" :row="row">
                  <div v-if="item.slot === 'handler'">
                    <!--status油站状态：0，已失效、10，待生效，20，生效中-->
                    <!--type：配置类型，1体验，2正式-->
                    <el-button size="mini" :class="{'notActive': row.type === 1}" @click="edit(row)" v-if="row.status === 10">修改</el-button>
                    <el-button size="mini" :class="{'notActive': row.type === 1}" @click="offLine(row)" v-if="row.status !== 0">下线</el-button>
                    <!--已失效-->
                    <span v-if="row.status === 0">—</span>
                  </div>
                  <!-- 开始生效时间-->
                  <div v-if="item.slot === 'beginTime'">
                    {{row.beginTime | formatTime('YYYY-MM-DD HH:mm:ss')}}
                  </div>
                  <!-- 生效结束时间-->
                  <div v-if="item.slot === 'endTime'">
                    {{row.endTime | formatTime('YYYY-MM-DD HH:mm:ss')}}
                  </div>
                  <!-- 置顶位置-->
                  <div v-if="item.slot === 'customLocation'">
                    {{'置顶位置' + row.customLocation}}
                  </div>
                  <!-- 公里数-->
                  <div v-if="item.slot === 'distanceRange'">
                    {{row.distanceRange + '公里'}}
                  </div>
                  <!-- 下线时间-->
                  <div v-if="item.slot === 'offlineTime'">
                    {{row.offlineTime | formatTime('YYYY-MM-DD HH:mm:ss')}}
                  </div>
                </slot>
              </template>
            </el-table-column>
          </template>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            v-if="tableData.totalRows"
            :layout="layout"
            :total="tableData.totalRows"
            :page-sizes="pageSizes"
            :current-page="params.pageNum"
            :page-size="params.pageSize"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            class="tablePagination">
        </el-pagination>
      </el-card>
    </div>
    <!--查询权限的情况-->
    <div v-if="tableData.display  === false" class="nodata-page">
      <img src="https://web.czb365.com/ty/merchant/no_sort_data1.png" class="no-data-img">
      <div class="tip">您还没有油站位置排序的使用权限</div>
      <div><el-button type="primary" @click="nowBuy">立即购买</el-button></div>
    </div>
  </div>
</template>

<script>
import { gasRankConfigQueryList, gasRankConfigQueryOffline, getAllGasInfoList } from '@/api/market'
// 表格参数配置
let tableConfig = [
    { label: '油站名称', prop: 'gasName', width: 150 },
    { label: '置顶位置', slot: 'customLocation', prop: 'customLocation', width: 130 },
    { label: '辐射半径', slot: 'distanceRange',prop: 'distanceRange', width: 130 },
    { label: '开始生效时间', slot: 'beginTime', prop: 'beginTime', width: 150 },
    { label: '生效结束时间', slot: 'endTime', prop: 'endTime', width: 150 },
    { label: '下线时间', slot: 'offlineTime', prop: 'offlineTime', width: 150 },
    { label: '状态', prop: 'statusStr', width: 136},
    { label: '操作', slot: 'handler', fixed: 'right', width: 150 }
]

export default {
  name: "locationSort",
  data () {
    return {
      tableConfig: tableConfig,
      tableData: {
        totalRows: 0,
        display: null
      }, // 列表数据
      selectedTime: '', // 选中的时间标签
      selectedStatus: '', // 选中的  状态标签
      loading: false,
      params: {
        beginTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 10,
        gasId: ''
      },
      oilStations: [],  // 油站列表
      pageSizes: [10, 20, 50, 100, 200],
      layout: "total, sizes, prev, pager, next, jumper",
      searchList: [{
        code: 1,
        value: '近7天'
      }, {
        code: 2,
        value: '近一个月'
      }, {
        code: 3,
        value: '近三个月'
      }],
      statusList: [{
        code: 20,
        value: '生效中'
      }, {
        code: 10,
        value: '待生效'
      }, {
        code: 0,
        value: '已结束'
      }]
    }
  },
  created() {
    // 获取登录用户信息
    this.loginInfo = JSON.parse(sessionStorage.getItem('loginInfo') || '{}')
  },
  mounted() {
    // 登录的若是商户需要查询油站列表
    if(this.loginInfo.company) {
      // 如果为页面跳转过来，需获取油站ID
      this.params.gasId = this.$route.query.gasId || ''
      // 获取油站列表
      this.getAllGasInfoListAjax()
    } else {
      // 登录的是油站直接获取列表
      this.gasRankConfigQueryListAjax()
    }
  },
  methods: {
    // 选择时间标签
    selectTime (item) {
      // 如果再次点击当前按钮，则取消选中
      if (this.selectedTime === item.code) {
        this.selectedTime = ''
      } else {
        this.selectedTime = item.code
      }
      this.initTime(this.selectedTime)
      this.params.pageNum = 1
      this.gasRankConfigQueryListAjax()
    },
    // 根据选择的时间标签进行时间的设置
    initTime (selectedTime) {
      if (!selectedTime) {
        this.params.beginTime = ''
        this.params.endTime = ''
        return false
      }
      let end = new Date()
      let start = new Date()
      switch (selectedTime) {
        case 1:
          // 近七天
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          break
        case 2:
          // 近一个月
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          break
        case 3:
          // 近三个月
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          break
      }
      this.params.beginTime = start.getTime()
      this.params.endTime = end.getTime()
    },
    // 选择状态标签
    selectStatus (item) {
      // 如果再次点击当前按钮，则取消选中
      if (this.selectedStatus === item.code) {
        this.selectedStatus = ''
      } else {
        this.selectedStatus = item.code
      }
      this.params.pageNum = 1
      this.gasRankConfigQueryListAjax()
    },
    // 获取油站列表
    async  getAllGasInfoListAjax () {
      try{
        const {code, result} = await getAllGasInfoList ()
        if (code !== 200) return
        this.oilStations = result || []
        // 如果油站ID为空，默认选择第一个油站
        if (!this.params.gasId) {
          this.params.gasId= this.oilStations[0].gasId
        }
        this.gasRankConfigQueryListAjax()
      } catch (err) {
          console.log(err)
      }
    },
    // 获取列表数据
    async  gasRankConfigQueryListAjax  () {
      try {
        this.loading = true
        let { gasId, beginTime, endTime, pageSize, pageNum} = this.params
        let data = {
          gasId: gasId || '',
          status: this.selectedStatus,
          beginTime,
          endTime,
          pageSize,
          pageNum
        }
        const { code, result } = await gasRankConfigQueryList(data)
        this.loading = false
        if (code !== 200) return
        this.tableData = result || {}
      }catch (err) {
         console.log(err)
      }
    },
    // 新增
    add () {
      // 跳转新增页面
      this.$router.push('/marketCenter/locationSortAdd')
    },
    // 修改
    edit (row) {
       // 配置类型，1体验，2正式
      if (row.type === 1 ) {
        this.$message.warning('您当前为体验用户，无操作权限')
        return false
      }
      // 跳转修改页面
      this.$router.push({path: '/marketCenter/locationSortAdd', query: {configId: row.configId}})
    },
    // 查询列表全部数据
    queryAllDataList () {
      this.selectedTime = ''
      this.initTime(this.selectedTime)
      this.selectedStatus = ''
      this.gasRankConfigQueryListAjax()
    },
    // 下线
    offLine (row) {
      // 配置类型，1体验，2正式
      if (row.type === 1 ) {
          this.$message.warning('您当前为体验用户，无操作权限')
          return false
      }
      // 油站状态：0，已失效、10，待生效，20，生效中
      let tip = ''
      if (row.status === 10) {
        tip = '活动下线后需要重新配置上线时间哦～'
      } else {
        tip = '现在下线将会扣除当天整天的活动时间哦！'
      }
      this.$confirm('确定要下线当前活动吗?' +'</br>'+ tip, '活动下线提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true
      }).then(() => {
          this.gasRankConfigQueryOfflineAjax(row)
      }).catch(() => {
          console.log('取消')
      })
    },
    // 下线操作
    async gasRankConfigQueryOfflineAjax (row) {
      try {
        let params = {
          configId: row.configId,
          sysSource: 2 // 商户
        }
        const { code } = await gasRankConfigQueryOffline (params)
        if (code !== 200) return
        this.$message.success('下线成功')
        // 重新请求列表
        this.gasRankConfigQueryListAjax()
      } catch(err) {
        console.log(err)
      }
    },
     // 调整每页数量
    handleSizeChange (val) {
      this.params.pageSize = val
      // 重新查询列表
      this.gasRankConfigQueryListAjax()
    },
    // 翻页
    handlePageChange (val) {
      this.params.pageNum = val
      this.gasRankConfigQueryListAjax()
    },
    // 油站切换
    oilStationChange () {
      // 重新请求列表
      this.gasRankConfigQueryListAjax()
    },
    // 立即购买
    nowBuy () {
      this.$router.push('/marketCenter/introduce')
    }
  }
}
</script>

<style lang="less" scoped>
.home-page-container {
  min-width: 885px;
  height: 100%;
  padding-top: 10px;
  box-sizing: border-box;
}
/deep/ .el-button.notActive {
  background: #F8F9FD;
  color: #C0C4CC;
}
.content-search {
  font-size: 14px;
  color: #606266;
  padding: 20px 20px;
  background: #ffffff;
  margin-bottom: 10px;
  font-weight: bold;
  .search-oilstation {
    padding-bottom: 15px;
    .label-text {
      display: inline-block;
      margin-right: 10px;
    }
  }
}
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: normal;
  .search-item {
    display: flex;
    align-items: center;
    .line {
      width: 1px;
      height: 24px;
      background: #4B7EFE;
      margin-right: 20px;
    }
    .btn-box {
      display: flex;
      .btn {
        min-width: 100px;
        text-align: center;
        margin-right: 20px;
        padding: 10px 0;
        border-radius: 2px;
        border: 1px solid #CCCCCC;
        color: #666666;
        font-size: 14px;
      }
      .btn.active {
        background: rgba(75, 126, 254, 0.1);
        color:#4B7EFE;
        border: 1px solid #4B7EFE;
      }
    }
  }
  .all {
    /deep/ .el-button {
      padding: 10px 35px;
      border-radius: 2px;
      border: 1px solid #CCCCCC;
      color: #666666;
      font-size: 14px;
      background: #fff;
    }
    /deep/ .el-button.active {
      background: #4B7EFE;
      color:#FFFFFF;
      border: 1px solid #4B7EFE;
    }
  }
}
.operation-box {
  margin-bottom: 10px;
  padding: 0 20px;
  .el-button {
    padding: 10px 35px;
    color: #4B7EFE;
    border: 1px solid #4B7EFE;
  }
}
.nodata-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .no-data-img {
    width: 273px;
    height: 250px;
  }
  .tip {
    color: #C5C5C5;
    font-size: 20px;
    margin: 20px 0 40px 0;
  }
  /deep/ .el-button {
    padding: 10px 50px;

  }
}
.tablePagination{
  margin: 15px 0;
  float: right;
}
</style>
